import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:meal/constant/fonts.dart';
import 'package:meal/constant/sizes.dart';
import 'package:meal/route/route.dart';
import 'package:meal/utils/colors.dart';
import 'package:meal/utils/styles.dart';
import 'package:meal/utils/tools.dart';
import 'package:sticky_headers/sticky_headers/widget.dart';
import 'package:time_machine/time_machine.dart';

///
/// 经营收款
///
///
class ManageProceed extends StatefulWidget {
  const ManageProceed({Key? key}) : super(key: key);

  @override
  State<ManageProceed> createState() => _ManageProceedState();
}

class _ManageProceedState extends State<ManageProceed> {
  late ScrollController controller;

  String rangeDay = '';

  List<_ProceedMonth> pages = [];

  Widget get actionWidget {
    return BrnIconAction(
      iconPressed: () {
        BrnDateRangePicker.showDatePicker(context,
            isDismissible: true,
            minDateTime: DateTime(2019, 01, 01),
            maxDateTime: DateTime.now(),
            pickerMode: BrnDateTimeRangePickerMode.date,
            minuteDivider: 30,
            pickerTitleConfig: const BrnPickerTitleConfig(titleContent: '选择日期范围'),
            dateFormat: 'yyyy-MM-dd',
            themeData: BrnPickerConfig(
                titleTextStyle: BrnTextStyle(
                    color: ColorsUtils.parseColorFromHexString(ColorsUtils.color333),
                    fontSize: Sizes.default15,
                    fontWeight: Fonts.w5)), onConfirm: (DateTime startDateTime,
                DateTime endDateTime, List<int> startList, List<int> endList) {
          /// 2021-11-16 至 2021-11-09
          setState(() {
            var dateFormat = DateFormat('yyyy-MM-dd');
            rangeDay = '${dateFormat.format(startDateTime)} 至 ${dateFormat.format(endDateTime)}';
            changeMonthData(startDateTime, endDateTime);
          });
          BrnToast.show('onConfirm: $startDateTime $endDateTime $startList $endList', context);
        });
      },
      size: Sizes.default16,
      child: ImageIcon(ToolsUtils.assetImageIcon('date.png')),
    );
  }

  void changeMonthData(DateTime startDateTime, DateTime endDateTime) {
    pages.clear();
    LocalDate start = LocalDate.dateTime(startDateTime);
    LocalDate end = LocalDate.dateTime(endDateTime);
    int months =
        (endDateTime.year - startDateTime.year) * 12 + (endDateTime.month - startDateTime.month);
    DateFormat format = DateFormat('yyyy-MM-dd');
    var days = endDateTime.day;
    for (var i = months; i > 0; i--) {
      double income = 0;
      List<_ProceedDate> data = [];
      if (i == months) {
        for (var j = days; j > 0; j--) {
          var money = 10.5;
          income += money;
          data.add(_ProceedDate(
              orders: 101,
              date: format.format(end.subtractDays(days - j).toDateTimeUnspecified()),
              income: money));
        }
        pages.add(_ProceedMonth(month: rangeDay, income: income, children: data));
      } else {
        LocalDate date = end.subtractMonths(months - i);
        String month =
            format.format(date.toDateTimeUnspecified()).replaceAll(RegExp('(-\\d{2})\$'), '');
        var monthDays = DateTime(date.year, date.monthOfYear + 1, 0).day;
        var now = DateTime(date.year, date.toDateTimeUnspecified().month, monthDays);
        for (var j = monthDays; j > 0; j--) {
          var money = 10.5;
          income += money;
          data.add(_ProceedDate(
              orders: 101,
              date: format.format(now.subtract(Duration(days: monthDays - j))),
              income: money));
        }
        pages.add(_ProceedMonth(month: month, income: income, children: data));
      }
    }

    var startDays = startDateTime.day;
    double amount = 0;
    List<_ProceedDate> data = [];
    for (var i = startDays; i > 0; i--) {
      var money = 10.5;
      amount += money;
      data.add(_ProceedDate(
          date: format.format(start.subtractDays(startDays - i).toDateTimeUnspecified()),
          type: i % 2,
          income: money,
          orders: 101));
    }
    pages.add(_ProceedMonth(
        month: format.format(startDateTime).replaceAll(RegExp('(-\\d{2})\$'), ''),
        income: amount,
        children: data));
  }

  @override
  void initState() {
    super.initState();
    controller = ScrollController();
    initData();
  }

  void initData() {
    pages.clear();
    pages.add(_ProceedMonth(month: '本月', income: 457.17, children: [
      _ProceedDate(orders: 104, date: '2022-11-12', income: 10.57, type: 0),
      _ProceedDate(orders: 104, date: '2022-11-12', income: 10.57),
      _ProceedDate(orders: 104, date: '2022-11-12', income: 10.57, type: 0),
      _ProceedDate(orders: 104, date: '2022-11-12', income: 10.57),
      _ProceedDate(orders: 104, date: '2022-11-12', income: 10.57, type: 0),
      _ProceedDate(orders: 104, date: '2022-11-12', income: 10.57),
    ]));
    pages.add(_ProceedMonth(month: '2022-10', income: 457.17, children: [
      _ProceedDate(orders: 104, date: '2022-11-12', income: 10.57, type: 0),
      _ProceedDate(orders: 104, date: '2022-11-12', income: 10.57),
      _ProceedDate(orders: 104, date: '2022-11-12', income: 10.57, type: 0),
      _ProceedDate(orders: 104, date: '2022-11-12', income: 10.57),
      _ProceedDate(orders: 104, date: '2022-11-12', income: 10.57, type: 0),
      _ProceedDate(orders: 104, date: '2022-11-12', income: 10.57),
    ]));
    pages.add(_ProceedMonth(month: '2022-09', income: 457.17, children: [
      _ProceedDate(orders: 104, date: '2022-11-12', income: 10.57, type: 0),
      _ProceedDate(orders: 104, date: '2022-11-12', income: 10.57),
      _ProceedDate(orders: 104, date: '2022-11-12', income: 10.57, type: 0),
      _ProceedDate(orders: 104, date: '2022-11-12', income: 10.57),
      _ProceedDate(orders: 104, date: '2022-11-12', income: 10.57, type: 0),
      _ProceedDate(orders: 104, date: '2022-11-12', income: 10.57),
    ]));
    pages.add(_ProceedMonth(month: '2022-08', income: 457.17, children: [
      _ProceedDate(orders: 104, date: '2022-11-12', income: 10.57, type: 0),
      _ProceedDate(orders: 104, date: '2022-11-12', income: 10.57),
      _ProceedDate(orders: 104, date: '2022-11-12', income: 10.57, type: 0),
      _ProceedDate(orders: 104, date: '2022-11-12', income: 10.57),
      _ProceedDate(orders: 104, date: '2022-11-12', income: 10.57, type: 0),
      _ProceedDate(orders: 104, date: '2022-11-12', income: 10.57),
    ]));
  }

  @override
  void dispose() {
    super.dispose();
    controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ToolsUtils.getDefaultBackgroundColor(),
      appBar: ToolsUtils.getDefaultBrnAppBar('经营收款', actions: actionWidget),
      body: ListView.builder(
        itemBuilder: (BuildContext context, int index) {
          var item = pages[index];
          return StickyHeaderBuilder(
            controller: controller,
            content: Column(
              children: item.children
                  .map((e) => InkWell(
                        child: Container(
                          height: Sizes.default80,
                          padding: const EdgeInsets.only(right: Sizes.default20),
                          decoration: const BoxDecoration(color: Colors.white),
                          child: Row(
                            children: [
                              Container(
                                width: 65,
                                alignment: Alignment.center,
                                child: ToolsUtils.getUrlImg(
                                    'https://cdn7.axureshop.com/demo/1525603/images/财务管理/u1849.png',
                                    width: 26,
                                    height: 30),
                              ),
                              Expanded(
                                  child: Container(
                                padding: const EdgeInsets.symmetric(vertical: Sizes.default10),
                                child: Column(
                                  children: [
                                    Container(
                                      height: Sizes.default30,
                                      alignment: Alignment.centerLeft,
                                      child: Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text('共${e.orders}单',
                                              style: StylesUtils.customTextStyle(
                                                  fontSize: Sizes.default15,
                                                  color: ColorsUtils.color333)),
                                          Text('${e.income}',
                                              style: StylesUtils.customTextStyle(
                                                  fontSize: Sizes.default15,
                                                  color: ColorsUtils.color333)),
                                        ],
                                      ),
                                    ),
                                    Container(
                                      height: Sizes.default30,
                                      alignment: Alignment.centerLeft,
                                      child: Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text(e.date,
                                              style: StylesUtils.customTextStyle(
                                                  fontSize: Sizes.default12,
                                                  color: ColorsUtils.color797)),
                                          Text(e.type == 1 ? '已入账' : '未入账',
                                              style: StylesUtils.customTextStyle(
                                                  fontSize: Sizes.default12,
                                                  color: ColorsUtils.color797)),
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                              ))
                            ],
                          ),
                        ),
                        onTap: () {
                          Get.toNamed(RouteGet.financeManagePayment);
                        },
                      ))
                  .toList(),
            ),
            builder: (BuildContext context, double stuckAmount) {
              stuckAmount = 1.0 - stuckAmount.clamp(0.0, 1.0);
              return Container(
                padding: const EdgeInsets.symmetric(
                    horizontal: Sizes.default15, vertical: Sizes.default10),
                decoration: BoxDecoration(
                  color: ToolsUtils.getDefaultBackgroundColor(),
                ),
                child: Row(
                  children: [
                    Expanded(
                        child: Column(
                      children: [
                        Container(
                          alignment: Alignment.centerLeft,
                          child: Text(
                            item.month,
                            style: StylesUtils.customTextStyle(color: ColorsUtils.color333),
                          ),
                        ),
                        Container(
                          alignment: Alignment.centerLeft,
                          margin: const EdgeInsets.only(top: Sizes.default10),
                          child: Text(
                            '已入账 ￥${item.income}',
                            style: StylesUtils.customTextStyle(
                                color: ColorsUtils.color797, fontSize: Sizes.default12),
                          ),
                        )
                      ],
                    )),
                    if (rangeDay.isNotEmpty)
                      Offstage(
                        offstage: stuckAmount <= 0.0,
                        child: Opacity(
                            opacity: stuckAmount,
                            child: Center(
                              child: TextButton(
                                  onPressed: () {
                                    rangeDay = '';
                                    setState(initData);
                                  },
                                  child: Text(
                                    '重置',
                                    style: StylesUtils.customTextStyle(
                                        fontSize: Sizes.default13, color: ColorsUtils.colorFf6),
                                  )),
                            )),
                      )
                  ],
                ),
              );
            },
          );
        },
        controller: controller,
        itemCount: pages.length,
      ),
    );
  }
}

class _ProceedMonth {
  /// 月份
  String month;

  /// 收入
  double income;

  List<_ProceedDate> children;

  _ProceedMonth({required this.month, required this.income, this.children = const []});
}

class _ProceedDate {
  /// 订单数
  int orders;

  /// 日期
  String date;

  /// 收入
  double income;

  /// 1 = 已入账, 0= 未入账
  int type;

  _ProceedDate({required this.orders, required this.date, required this.income, this.type = 1});
}
